﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Helena.Areas.Reportes.Models;
using Helena.Models;
using System.Data;
using Helena.Areas.Productos.Models;
using System.IO;
using System.Text;
using Helena.Areas.Ventas.Models;
using Helena.Areas.Vendedores.Models;
using Telerik.Web.Mvc;

namespace Helena.Areas.Reportes.Controllers
{
    public class KardexController : Controller
    {
        LogicaKardex db = new LogicaKardex();
        LogicaProducto pro_db = new LogicaProducto();
        LogicaVenta vnt_db = new LogicaVenta();
        LogicaCierreCaja cierre = new LogicaCierreCaja();
        
        //
        // GET: /Reportes/Kardex/

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            if (vw.ID != 0)
            {
                return View();
            }
            else
            {
                return Redirect("../Home/NoSession");
            }
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult MostrarKardexMensual()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            if (vw.ID != 0)
            {
                Fecha Fecha = new Fecha();
                Fecha.anho = new List<year>();
                Fecha.mes = new List<Month>();
                for (int i = 2012; i < 2031; i++)
                {
                    year y = new year();
                    y.ID = i;
                    y.Descripcion = i;
                    Fecha.anho.Add(y);
                }
                Month m1 = new Month(1, "Enero");
                Fecha.mes.Add(m1);
                Month m2 = new Month(2, "Febrero");
                Fecha.mes.Add(m2);
                Month m3 = new Month(3, "Marzo");
                Fecha.mes.Add(m3);
                Month m4 = new Month(4, "Abril");
                Fecha.mes.Add(m4);
                Month m5 = new Month(5, "Mayo");
                Fecha.mes.Add(m5);
                Month m6 = new Month(6, "Junio");
                Fecha.mes.Add(m6);
                Month m7 = new Month(7, "Julio");
                Fecha.mes.Add(m7);
                Month m8 = new Month(8, "Agosto");
                Fecha.mes.Add(m8);
                Month m9 = new Month(9, "Septiembre");
                Fecha.mes.Add(m9);
                Month m10 = new Month(10, "Octubre");
                Fecha.mes.Add(m10);
                Month m11 = new Month(11, "Noviembre");
                Fecha.mes.Add(m11);
                Month m12 = new Month(12, "Diciembre");
                Fecha.mes.Add(m12);
                Session["Fecha"] = Fecha;
                return View();                
            }
            else
            {
                return Redirect("../../Home/NoSession");
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult MostrarKardexMensual(string anho, string mes)
        {
            DateTime fecha = new DateTime(Convert.ToInt32(anho), Convert.ToInt16(mes), 1);
            List<Kardex> kardex = db.MostrarKardexMensual(fecha);
            List<KardexSalida> salida = CrearTablaMensual(kardex, fecha);
            Session["Productos"] = pro_db.i_RetornarProductos().Where(p => p.Estado == true).ToList();
            return ExportarExcelMensual();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult MostrarKardexDiario()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            if (vw.ID != 0)
            {
                List<Kardex> k = new List<Kardex>();
                k.Add(new Kardex());
                return View(k);
            }
            else
            {
                return Redirect("../../Home/NoSession");
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult MostrarKardexDiario(DateTime Fecha)
        {
            List<Kardex> kardex = db.MostrarKardexDiario(Fecha);
            Session["KardexSalida"] = kardex;

            if (kardex.Count == 0)
            {
                List<Kardex> k = new List<Kardex>();
                k.Add(new Kardex());
                return View("MostrarKardexDiario", k);
            }
            else
            {
                return ExportarExcelDiario();
            }

        }

        public List<KardexSalida> CrearTablaMensual(List<Kardex> kardexDesorden, DateTime Fecha)
        {

            int DaysOfMonth = DateTime.DaysInMonth(Fecha.Year, Fecha.Month);
            List<ProductoView> productos = (from u in pro_db.i_RetornarProductos()
                                            where u.Estado == true
                                            orderby u.ID ascending
                                            select u).ToList();
            List<Kardex> kardexOrdenado = (from i in kardexDesorden
                                           orderby i.ProductoID ascending
                                           select i).ToList();

            List<KardexSalida> salida = new List<KardexSalida>();


            for (int i = 1; i <= DaysOfMonth; i++)
            {

                List<Kardex> Kardex = (from j in kardexOrdenado
                                       where j.Fecha.Day == i
                                       select j).ToList();

                DateTime f = new DateTime(Fecha.Year, Fecha.Month, i);

                KardexSalida s = new KardexSalida(f);

                foreach (Kardex k in Kardex)
                {
                    foreach (ProductoView pw in productos)
                    {
                        if (pw.ID == k.ProductoID)
                        {
                            s.kardex.Add(k);
                        }
                    }
                }

                salida.Add(s);
            }
            Session["KardexSalida"] = salida;
            return salida;
        }

        public ActionResult ExportarExcelMensual()
        {
            List<KardexSalida> salida = (List<KardexSalida>)Session["KardexSalida"];

            String excel = String.Empty;
            
            List<ProductoView> lproductos = pro_db.i_RetornarProductos().Where(p => p.Estado == true).ToList();
            List<ProductoView> productos = new List<ProductoView>();

            foreach (ProductoView p in lproductos)
            {
                List<DetalleProductoView> d = pro_db.DetallesDeUnProducto(p.ID);
                if (d.Count == 0)
                {
                    productos.Add(p);
                }
            }
            
            foreach (KardexSalida ks in salida)
            {
                excel += ks.Fecha.Day.ToString() + "Producto¬";
                excel += ks.Fecha.Day.ToString() + "CantidadIncial¬";
                excel += ks.Fecha.Day.ToString() + "Entrada¬";
                excel += ks.Fecha.Day.ToString() + "Salida¬";
                excel += ks.Fecha.Day.ToString() + "Degustacion¬";
                excel += ks.Fecha.Day.ToString() + "Venta¬";
                excel += ks.Fecha.Day.ToString() + "CantidadFinal¬";
            }
            excel += "°";

            int cantidad = productos.Count;
            int i = 1;
            bool pivote = false;

            foreach (ProductoView p in productos)
            {


                for (int dia = 1; dia <= salida.Count; dia++)
                {
                    pivote = false;
                    KardexSalida ks = salida.Where(k => k.Fecha.Day == dia).SingleOrDefault();
                    foreach (Kardex k in ks.kardex)
                    {
                        if (p.ID == k.ProductoID)
                        {
                            pivote = true;
                            excel += k.ProducttoDescripcion.ToString() + "¬";
                            excel += k.CantidadInicial.ToString() + "¬";
                            excel += k.Entrada.ToString() + "¬";
                            excel += k.Salida.ToString() + "¬";
                            excel += k.Degustacion.ToString() + "¬";
                            excel += k.Venta.ToString() + "¬";
                            excel += k.CantidadFinal.ToString() + "¬";

                        }
                    }

                    if (pivote == false)
                    {
                        excel += p.Descripcion + "¬";
                        excel += "0" + "¬";
                        excel += "0" + "¬";
                        excel += "0" + "¬";
                        excel += "0" + "¬";
                        excel += "0" + "¬";
                        excel += "0" + "¬";
                    }
                }

                excel += "°";
            }

            string[] reporte = excel.Split(new Char[] { '°' });

            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
            foreach (string r in reporte)
            {
                string[] subreporte = r.Split(new Char[] { '¬' });
                foreach (string sr in subreporte)
                {
                    writer.Write(sr);
                    writer.Write(",");
                }
                writer.WriteLine();
                writer.Flush();
            }

            output.Position = 0;

            return File(output, "text/comma-separated-values", "Kardex_Mensual" + DateTime.Now.ToShortDateString() + ".csv");
        }

        public ActionResult ExportarExcelDiario()
        {
            List<Kardex> salida = (List<Kardex>)Session["KardexSalida"];
            DateTime fecha = new DateTime();
            
            String excel = String.Empty;
            List<ProductoView> productos = pro_db.i_RetornarProductos().Where(p => p.Estado == true).ToList();
            excel += "Producto¬";
            excel += "CantidadIncial¬";
            excel += "Entrada¬";
            excel += "Salida¬";
            excel += "Degustacion¬";
            excel += "Venta¬";
            excel += "CantidadFinal¬";
            excel += "°";

            foreach (Kardex k in salida)
            {
                fecha = k.Fecha;
                excel += k.ProducttoDescripcion.ToString() + "¬";
                excel += k.CantidadInicial.ToString() + "¬";
                excel += k.Entrada.ToString() + "¬";
                excel += k.Salida.ToString() + "¬";
                excel += k.Degustacion.ToString() + "¬";
                excel += k.Venta.ToString() + "¬";
                excel += k.CantidadFinal.ToString() + "¬";
                excel += "°";

            }

            string[] reporte = excel.Split(new Char[] { '°' });

            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
            foreach (string r in reporte)
            {
                string[] subreporte = r.Split(new Char[] { '¬' });
                foreach (string sr in subreporte)
                {
                    writer.Write(sr);
                    writer.Write(",");
                }
                writer.WriteLine();
                writer.Flush();
            }

            List<VentaView> ventas = vnt_db.i_RetornarVentas().Where(v => v.Fecha.DayOfYear == fecha.DayOfYear).ToList();
            CierreCaja c = cierre.ObtenerCierraCaja(fecha);

            writer.Write(""); writer.Write(",");writer.Write("");writer.Write(",");writer.Write("");writer.Write(",");writer.Write(""); writer.Write(",");
            writer.Write("Total Venta Bruta"); writer.Write(","); writer.Write(c.TotalVentaBruta); writer.Write(","); writer.WriteLine(); writer.Flush();

            writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(",");
            writer.Write("Total Descuento"); writer.Write(","); writer.Write(c.TotalDescuento); writer.Write(","); writer.WriteLine(); writer.Flush();

            writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(",");
            writer.Write("Total Venta Neta"); writer.Write(","); writer.Write(c.TotalVentaNeta); writer.Write(","); writer.WriteLine(); writer.Flush();

            writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(",");
            writer.Write("Pagos en Dolares"); writer.Write(","); writer.Write(c.Pagos_de_Venta_en_Dolares); writer.Write(","); writer.WriteLine(); writer.Flush();

            writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(",");
            writer.Write("Total Pago Tarjeta Soles"); writer.Write(","); writer.Write(c.Pagos_de_venta_TarjetaSoles); writer.Write(","); writer.WriteLine(); writer.Flush();

            writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(","); writer.Write(""); writer.Write(",");
            writer.Write("Tipo de Cambio"); writer.Write(","); writer.Write(c.TipoCambio); writer.Write(","); writer.WriteLine(); writer.Flush();
                            
            writer.WriteLine();
            writer.Flush();

            output.Position = 0;

            return File(output, "text/comma-separated-values", "Kardex_Diario_" + DateTime.Now.ToShortDateString() + ".csv");
        }
    }
}
